<template>
  <div class="form-container" v-loading="loading">
    <div class="top">
      <el-form size="mini" ref="form" :model="form" label-width="120px">
        <el-form-item prop="keywords" label="关键词">
          <el-input class="long" maxlength="20" v-model="form.keywords" placeholder="例如：名称、品牌、参数等（不超过20个字）"></el-input>
          <el-tag size="small" style="cursor: pointer" @click="handleAddKeywords" type="danger">添加 +</el-tag>
          <div class="keyword-list" style="margin-bottom: 5px">
            <el-tag size="small" v-for="(item, index) in keywordsList" disable-transitions @close="handleDeleteKeywords(index)" :key="item + index" closable type="info" style="margin-right: 5px">
              {{ item }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="bottom">
      <el-divider></el-divider>
      <div class="line">
        <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { apiLoveWordsSave } from '@/api/assetsDisposal'

export default {
  props: {
    keywords: {
      type: Array,
      default: [],
    },
    userId: String,
  },
  data() {
    return {
      loading: false,
      form: {
        keywords: '', // 输入框输入的关键词
      },
      keywordsList: [], // 关键词列表
    }
  },
  mounted() {
    this.keywordsList = [...this.keywords]
  },
  methods: {
    // 确定
    onSubmit() {
      const form = {
        user_id: this.userId,
        words: this.keywordsList.join(','),
      }
      const formData = new FormData()
      for (let key in form) {
        formData.set(key, form[key])
      }
      apiLoveWordsSave(formData).then((res) => {
        if (res.code === 200) {
          this.$emit('confirm')
        }
      })
    },
    // 添加关键字
    handleAddKeywords() {
      if (!this.form.keywords) {
        return
      }
      this.keywordsList.push(this.form.keywords)
      this.form.keywords = ''
    },
    // 删除关键字
    handleDeleteKeywords(index) {
      this.keywordsList.splice(index, 1)
    },
  },
}
</script>
<style lang="scss" scoped>
.form-container {
  padding: 0 24px;
  .top {
    min-height: 300px;
  }
  .bottom {
    .line {
      display: flex;
      justify-content: flex-end;
    }
  }
  .el-cascader {
    width: 100%;
    .el-input {
      width: 100% !important;
      margin: 0 !important;
    }
  }
  .el-input {
    width: 150px !important;
    margin: 0 5px !important;
  }
  .long.el-input {
    width: 83% !important;
    margin: 0 !important;
    margin-right: 20px !important;
  }

  .line {
    display: inline-block;
    margin-left: 10px;
  }
}
</style>

<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}
</style>
